# Maintainer: Alexey Pavlov <Alexpux@gmail.com>
# Contributor: Renato Silva <br.renatosilva@gmail.com>
# Contributor: Niklas Holm <jadedcyborg@gmail.com>

# Order is important, primary package first
declare -rga _realname=(perl perl-doc)
url='https://www.perl.org'
pkgdesc='A highly capable, feature-rich programming language (mingw-w64)'
license=(GPL1+ Artistic1)
arch=(any)
# If you are upgrading to a new version, please run setup_perl_dirs.sh on the
# (patched) source tree to update hard-coded path values. If there are any
# changes, update the exisitng patches or add a new one.
pkgver=5.26.1
pkgrel=1
options=(staticlibs strip '!purge' emptydirs)
pkgbase="mingw-w64-${_realname}"
pkgname=()
declare -ga _pkgname=()
# Associative array to map current pkgname (in package_x()) to realname
declare -gA _pkgname_ht=()
local _n _p
for _n in "${_realname[@]}"; do
    _p="${MINGW_PACKAGE_PREFIX}-${_n}"
    _pkgname_ht+=(["${_p}"]="${_n}")
    _pkgname+=("${_p}")
    pkgname+=("${_p}")
done
readonly _pkgname _pkgname_ht
makedepends=(
    ${MINGW_PACKAGE_PREFIX}-gcc
)
depends=(
    ${MINGW_PACKAGE_PREFIX}-gcc-libs
    ${MINGW_PACKAGE_PREFIX}-winpthreads
    ${MINGW_PACKAGE_PREFIX}-make
)
declare -rga _sources=(
    perlprofile.in
    perlinstall.in
)
if [[ -z "${SRCURI:-}" ]]; then
declare -rga _patches=(
    001-fhs-directory-structure.patch
    002-relocate-html-documentation.patch
    003-replace-batch-scripts-with-bare-perl.patch
    004-fix-cpan-external-programs.patch
    005-rename-cpan-home.patch
    006-generate-manpages.patch
)
source=(
    "https://www.cpan.org/src/5.0/${_realname}-${pkgver}.tar.xz"
    "${_patches[@]}"
    "${_sources[@]}"
)
else
source=(
    "${_realname}-${pkgver}::${SRCURI}"
    "${_sources[@]}"
)
SKIPCHECKSUMS=1
fi
## Populated by the patchprov script found at
## https://github.com/Alexpux/MSYS2-packages/blob/master/perl/patchprov
## and edited manually to add package prefix.
provides=("${MINGW_PACKAGE_PREFIX}-perl-archive-tar=2.24"
          "${MINGW_PACKAGE_PREFIX}-perl-attribute-handlers=0.99"
          "${MINGW_PACKAGE_PREFIX}-perl-autodie=2.29"
          "${MINGW_PACKAGE_PREFIX}-perl-autoloader=5.74"
          "${MINGW_PACKAGE_PREFIX}-perl-autouse=1.11"
          "${MINGW_PACKAGE_PREFIX}-perl-b-debug=1.24"
          "${MINGW_PACKAGE_PREFIX}-perl-base=2.26"
          "${MINGW_PACKAGE_PREFIX}-perl-bignum=0.47"
          "${MINGW_PACKAGE_PREFIX}-perl-carp=1.42"
          "${MINGW_PACKAGE_PREFIX}-perl-compress-raw-bzip2=2.074"
          "${MINGW_PACKAGE_PREFIX}-perl-compress-raw-zlib=2.074"
          "${MINGW_PACKAGE_PREFIX}-perl-config-perl-v=0.28"
          "${MINGW_PACKAGE_PREFIX}-perl-constant=1.33"
          "${MINGW_PACKAGE_PREFIX}-perl-cpan-meta-requirements=2.140"
          "${MINGW_PACKAGE_PREFIX}-perl-cpan-meta-yaml=0.018"
          "${MINGW_PACKAGE_PREFIX}-perl-cpan-meta=2.150010"
          "${MINGW_PACKAGE_PREFIX}-perl-cpan=2.18"
          "${MINGW_PACKAGE_PREFIX}-perl-data-dumper=2.167"
          "${MINGW_PACKAGE_PREFIX}-perl-db_file=1.840"
          "${MINGW_PACKAGE_PREFIX}-perl-devel-ppport=3.35"
          "${MINGW_PACKAGE_PREFIX}-perl-devel-selfstubber=1.06"
          "${MINGW_PACKAGE_PREFIX}-perl-digest-md5=2.55"
          "${MINGW_PACKAGE_PREFIX}-perl-digest-sha=5.96"
          "${MINGW_PACKAGE_PREFIX}-perl-digest=1.17_01"
          "${MINGW_PACKAGE_PREFIX}-perl-dumpvalue=1.18"
          "${MINGW_PACKAGE_PREFIX}-perl-encode=2.88"
          "${MINGW_PACKAGE_PREFIX}-perl-encoding-warnings=0.13"
          "${MINGW_PACKAGE_PREFIX}-perl-env=1.04"
          "${MINGW_PACKAGE_PREFIX}-perl-experimental=0.016"
          "${MINGW_PACKAGE_PREFIX}-perl-exporter=5.72"
          "${MINGW_PACKAGE_PREFIX}-perl-extutils-cbuilder=0.280225"
          "${MINGW_PACKAGE_PREFIX}-perl-extutils-constant=0.23"
          "${MINGW_PACKAGE_PREFIX}-perl-extutils-install=2.04"
          "${MINGW_PACKAGE_PREFIX}-perl-extutils-makemaker=7.24"
          "${MINGW_PACKAGE_PREFIX}-perl-extutils-manifest=1.70"
          "${MINGW_PACKAGE_PREFIX}-perl-extutils-parsexs=3.34"
          "${MINGW_PACKAGE_PREFIX}-perl-file-fetch=0.52"
          "${MINGW_PACKAGE_PREFIX}-perl-file-path=2.12_01"
          "${MINGW_PACKAGE_PREFIX}-perl-file-temp=0.2304"
          "${MINGW_PACKAGE_PREFIX}-perl-filter-simple=0.93"
          "${MINGW_PACKAGE_PREFIX}-perl-filter-util-call=1.55"
          "${MINGW_PACKAGE_PREFIX}-perl-getopt-long=2.49"
          "${MINGW_PACKAGE_PREFIX}-perl-http-tiny=0.070"
          "${MINGW_PACKAGE_PREFIX}-perl-i18n-collate=1.02"
          "${MINGW_PACKAGE_PREFIX}-perl-i18n-langtags=0.42"
          "${MINGW_PACKAGE_PREFIX}-perl-if=0.0606"
          "${MINGW_PACKAGE_PREFIX}-perl-io-compress=2.074"
          "${MINGW_PACKAGE_PREFIX}-perl-io-socket-ip=0.38"
          "${MINGW_PACKAGE_PREFIX}-perl-io-zlib=1.10"
          "${MINGW_PACKAGE_PREFIX}-perl-io=1.38"
          "${MINGW_PACKAGE_PREFIX}-perl-ipc-cmd=0.96"
          "${MINGW_PACKAGE_PREFIX}-perl-ipc-sysv=2.07"
          "${MINGW_PACKAGE_PREFIX}-perl-json-pp=2.27400_02"
          "${MINGW_PACKAGE_PREFIX}-perl-lib=0.64"
          "${MINGW_PACKAGE_PREFIX}-perl-libnet=3.10"
          "${MINGW_PACKAGE_PREFIX}-perl-locale-codes=3.42"
          "${MINGW_PACKAGE_PREFIX}-perl-locale-maketext-simple=0.21_01"
          "${MINGW_PACKAGE_PREFIX}-perl-locale-maketext=1.28"
          "${MINGW_PACKAGE_PREFIX}-perl-math-bigint-fastcalc=0.5005"
          "${MINGW_PACKAGE_PREFIX}-perl-math-bigint=1.999806"
          "${MINGW_PACKAGE_PREFIX}-perl-math-bigrat=0.2611"
          "${MINGW_PACKAGE_PREFIX}-perl-math-complex=1.5901"
          "${MINGW_PACKAGE_PREFIX}-perl-memoize=1.03_01"
          "${MINGW_PACKAGE_PREFIX}-perl-mime-base64=3.15"
          "${MINGW_PACKAGE_PREFIX}-perl-module-corelist=5.20170922_26"
          "${MINGW_PACKAGE_PREFIX}-perl-module-load-conditional=0.68"
          "${MINGW_PACKAGE_PREFIX}-perl-module-load=0.32"
          "${MINGW_PACKAGE_PREFIX}-perl-module-loaded=0.08"
          "${MINGW_PACKAGE_PREFIX}-perl-module-metadata=1.000033"
          "${MINGW_PACKAGE_PREFIX}-perl-net-ping=2.55"
          "${MINGW_PACKAGE_PREFIX}-perl-params-check=0.38"
          "${MINGW_PACKAGE_PREFIX}-perl-parent=0.236"
          "${MINGW_PACKAGE_PREFIX}-perl-pathtools=3.67"
          "${MINGW_PACKAGE_PREFIX}-perl-perl-ostype=1.010"
          "${MINGW_PACKAGE_PREFIX}-perl-perlfaq=5.021011"
          "${MINGW_PACKAGE_PREFIX}-perl-perlio-via-quotedprint=0.08"
          "${MINGW_PACKAGE_PREFIX}-perl-pod-checker=1.73"
          "${MINGW_PACKAGE_PREFIX}-perl-pod-escapes=1.07"
          "${MINGW_PACKAGE_PREFIX}-perl-pod-parser=1.63"
          "${MINGW_PACKAGE_PREFIX}-perl-pod-perldoc=3.28"
          "${MINGW_PACKAGE_PREFIX}-perl-pod-simple=3.35"
          "${MINGW_PACKAGE_PREFIX}-perl-pod-usage=1.69"
          "${MINGW_PACKAGE_PREFIX}-perl-podlators=5.006"
          "${MINGW_PACKAGE_PREFIX}-perl-safe=2.40"
          "${MINGW_PACKAGE_PREFIX}-perl-scalar-list-utils=1.46_02"
          "${MINGW_PACKAGE_PREFIX}-perl-search-dict=1.07"
          "${MINGW_PACKAGE_PREFIX}-perl-selfloader=1.23"
          "${MINGW_PACKAGE_PREFIX}-perl-socket=2.020_03"
          "${MINGW_PACKAGE_PREFIX}-perl-storable=2.62"
          "${MINGW_PACKAGE_PREFIX}-perl-sys-syslog=0.35"
          "${MINGW_PACKAGE_PREFIX}-perl-term-ansicolor=4.06"
          "${MINGW_PACKAGE_PREFIX}-perl-term-cap=1.17"
          "${MINGW_PACKAGE_PREFIX}-perl-term-complete=1.403"
          "${MINGW_PACKAGE_PREFIX}-perl-term-readline=1.16"
          "${MINGW_PACKAGE_PREFIX}-perl-test-harness=3.38"
          "${MINGW_PACKAGE_PREFIX}-perl-test-simple=1.302073"
          "${MINGW_PACKAGE_PREFIX}-perl-test=1.30"
          "${MINGW_PACKAGE_PREFIX}-perl-text-abbrev=1.02"
          "${MINGW_PACKAGE_PREFIX}-perl-text-balanced=2.03"
          "${MINGW_PACKAGE_PREFIX}-perl-text-parsewords=3.30"
          "${MINGW_PACKAGE_PREFIX}-perl-text-tabs=2013.0523"
          "${MINGW_PACKAGE_PREFIX}-perl-thread-queue=3.12"
          "${MINGW_PACKAGE_PREFIX}-perl-thread-semaphore=2.13"
          "${MINGW_PACKAGE_PREFIX}-perl-threads-shared=1.56"
          "${MINGW_PACKAGE_PREFIX}-perl-threads=2.15"
          "${MINGW_PACKAGE_PREFIX}-perl-tie-file=1.02"
          "${MINGW_PACKAGE_PREFIX}-perl-tie-refhash=1.39"
          "${MINGW_PACKAGE_PREFIX}-perl-time-hires=1.9741"
          "${MINGW_PACKAGE_PREFIX}-perl-time-local=1.25"
          "${MINGW_PACKAGE_PREFIX}-perl-time-piece=1.31"
          "${MINGW_PACKAGE_PREFIX}-perl-unicode-collate=1.19"
          "${MINGW_PACKAGE_PREFIX}-perl-unicode-normalize=1.25"
          "${MINGW_PACKAGE_PREFIX}-perl-version=0.9917"
          "${MINGW_PACKAGE_PREFIX}-perl-xsloader=0.27")
## End of patchprov modifications

## Run updpkgsums to update
sha256sums=('fe8208133e73e47afc3251c08d2c21c5a60160165a8ab8b669c43a420e4ec680'
            'e08491b314a125e8b6aad211eed18e7fde1d2db9a6aea1b4a77d837c3efbc12a'
            'ccfc7c417e109790046e41cd425e09c91214f72e4cea7138ffb69bb8cb9eb313'
            '726cabf22ec69923bf2253ff7d8f504b0698054da909a812d1d6716ce4d1320b'
            '33bf80656a00e050f25da056eef69781701ecaf2dc4608b0049fefc938decca5'
            'b6055ad4e61133bf819cb50a36bac8a848c8649bcca70e4d0e48da60edd200e5'
            '611427bc16f389000c5d030db7351507e36583c8ae9f1a3d20a019ffbe96cdc8'
            '54d8a5fc218031ee1354c8780a7af5de64f712ad63abdf029b09d33b664d6b0f'
            'ff2bbc16a26d0583f344a8c88a055a5396c8b0d15e2498169c1ff996ca0d74ae')

declare -rg _build="build-${CARCH}-${_realname}-${pkgver}"

prepare() {
    cd "${srcdir}/${_realname}-${pkgver}"
    attrib.exe -r //s
    local p
    for p in "${_patches[@]}"; do
        msg2 "Applying %s" "$p"
        patch -p1 -i "${srcdir}"/"$p"
    done
}

_make() {
    # Please read README.win32 in the source package.
    # Using pkgdirbase here is not supported but required since we need the
    # package directory at build time, something which makepkg doesn't consider.
    local prefix="$(cygpath -w "${pkgdirbase}/${_pkgname[0]}${MINGW_PREFIX}")"
    local docprefix="$(cygpath -w "${pkgdirbase}/${_pkgname[1]}${MINGW_PREFIX}")"
    local cchome="$(cygpath -w "${MINGW_PREFIX}")"
    local sysroot="$(cygpath -u "${SYSTEMROOT}")"
    local -i jobs="${JOBS:-$(nproc)}"
    # README.win32 recommends bulding under Windows' default shell (cmd.exe)
    # and win32/makefile.mk recommends setting SHELL to it as well
    local cmd="$(cygpath -u "${COMSPEC}")"
    local cmdline=(
        "${cmd}" //C mingw32-make
        -j"${jobs}"
        TEST_JOBS="${jobs}"
        CCTYPE=GCC
        CCHOME="${cchome}"
        INST_DRV="${prefix:0:2}"
        INST_TOP="${prefix}"
        INST_DOC="${docprefix}"
        SHELL="${COMSPEC}"
        PLMAKE=mingw32-make
    )
    if [[ "$(uname --machine)" == "x86_64" && "${CARCH}" == "i686" ]]; then
        cmdline+=(WIN64=undef)
    fi
    cd "${srcdir}/${_build}/win32"
    msg2 "Running \"%s\"" "${cmdline[*]}$( (($#)) && echo -n " $*")"
    # Setting PATH here is not strictly necessary but it might make compilation
    # slightly faster to have the mostly used commands early on the PATH and
    # avoids interference with other programs on the PATH during tests.
    PATH="${sysroot}/system32:${sysroot}:${MINGW_PREFIX}/bin" "${cmdline[@]}" "$@"
}

build() {
    if [[ -e "${srcdir}/${_build}" ]]; then
        local -i i=1
        while [[ -e "${srcdir}/${_build}~${i}" ]]; do ((++i)); done
        mv -T "${srcdir}/${_build}" "${srcdir}/${_build}~${i}"
    fi
    mv -T "${srcdir}/${_realname}-${pkgver}" "${srcdir}/${_build}"
    local postfix
    [[ "${CARCH}" == "x86_64" ]] && postfix="w64" || postfix="w32"
    sed -ri "/@@CPAN_HOME@@/{N;s/([\._])cpan/\1cpan-${postfix}/g;D}" \
        "${srcdir}/${_build}/cpan/CPAN/lib/CPAN/HandleConfig.pm"
    _make
}

check() {
    # Some tests will fail, this is expected on Windows. Still, it might be good
    # to have this information in the build logs.
    _make test || true
}

eval "package_${_pkgname[0]}() { _package_bare; }" # perl
eval "package_${_pkgname[1]}() { _package_doc; }"  # perl-doc

_package_common() {
    install="${pkgname}.install"

    cd "${pkgdir}${MINGW_PREFIX}"
    attrib.exe -r //s

    msg2 "Cleaning up"
    find -O3 . \( -type f \( \
        -name '.packlist' -o -name 'perllocal.pod' -o -name '*.tmp' \
        -o -name '*.pod' ! -path '*/pods/*' \
        \) -o -type d -empty \) -delete

    # Path relocation. This is done by replacing hard-coded paths with relocate
    # patterns that will be resolved on package installation.

    local grep_args=() sed_args=() paths=() single= double= html= path=
    mapfile -t -d $'\0' paths < <(printf "${pkgdirbase}/%s/\0" "${_pkgname[@]}")
    for path in "${paths[@]}" /; do
        single="$(cygpath -w "${path}")"
        single="${single//\\/\\\\}"        # \  -> \\
        double="${single//\\\\/\\\\\\\\}"  # \\ -> \\\\
        html="${single//\\\\/\\\/}"        # \\ -> \/
        grep_args+=(
            -e "${html}"
            -e "${double}"
            -e "${single}"
        )
        sed_args+=(
            -e "s/${html}/@PERL_RELOCATE_HTML@\\//g"
            -e "s/${double}/@PERL_RELOCATE_DOUBLE@\\\\\\\\/g"
            -e "s/${single}/@PERL_RELOCATE@\\\\/g"
        )
    done

    msg2 "Creating relocate patterns for:"
    local -i i
    for ((i=0; i<${#grep_args[@]}; ++i)); do
        if ((i%2 == 1)); then
            plain "%b" "${grep_args[i]}"
        fi
    done

    # Attach list of files containing relocate patterns for use in post-install script.
    # Update perl-*.install if changing the filename.
    local relocate_list="./share/${_pkgname_ht["${pkgname}"]}/.relocate_list"
    install -Dvm644 <(grep -rilZ "${grep_args[@]}" . ) "${relocate_list}"

    xargs -0 -a "${relocate_list}" sed -i "${sed_args[@]}"

    install -Dvm644 <(sed \
            -e "s/@PREFIX@/${MINGW_PREFIX//\//\\\/}/g" \
            -e "s/@FILELIST@/${relocate_list//\//\\\/}/g" \
            -e "/@REM@/d" \
            "${srcdir}"/perlinstall.in) \
        "${startdir}/${install}"
}

_package_doc() {
    pkgdesc="Perl manpages and html documentation (mingw-64)"
    optdepends=("${_pkgname[0]}")
    provides=()
    _make install.doc
    _package_common
}

_package_bare() {
    optdepends=("${_pkgname[1]}")
    _make install.bare
    _package_common

    msg2 "Post-install configuration"
    local config_heavy="$(find . -name Config_heavy.pl -print -quit)"

    ### Perl Settings ###
    # Change man page extensions for site and vendor module builds.
    sed -i -e '/^man1ext=/ s/=.*/='"'"'1p'"'"'/' \
           -e '/^man3ext=/ s/=.*/='"'"'3pm'"'"'/' \
           "${config_heavy}"

    msg2 "Getting PATH components"
    local skip_paths=("${MINGW_PREFIX}/bin")
    local path_arr=()
    # Parse the configuration for paths that should be added to PATH
    # The sorting is a bit hacky...
    local p
    while IFS='' read -r p; do
        p="${p//\\/\/}"
        if [[ -n "${p}" \
              && ! "$(printf '%s\n' "${skip_paths[@]}" "${path_arr[@]}")" \
              =~ (^|$'\n')"${p}"($'\n'|$) ]]; then
            path_arr+=("${p}")
        fi
    done < <(\
        sed -nr \
            -e "s/^installsitebin='@PERL_.*?@(.*)'/1\\t\\1/p" \
            -e "s/^installsitescript='@PERL_.*?@(.*)'/2\\t\\1/p" \
            -e "s/^installvendorbin='@PERL_.*?@(.*)'/3\\t\\1/p" \
            -e "s/^installvendorscript='@PERL_.*?@(.*)'/4\\t\\1/p" \
            -e "s/^installbin='@PERL_.*?@(.*)'/5\\t\\1/p" \
            -e "s/^installscript='@PERL_.*?@(.*)'/6\\t\\1/p" \
            "${config_heavy}" \
        | sort -n -k1,1 | cut -f2- | uniq
    )
    local path="$(IFS=':'; echo "${path_arr[*]}")"

    msg2 "Adding extra files"
    local profile="/etc/profile.d/z-${_realname}-${CARCH}.sh"
    install -Dvm644 <(sed \
            -e "/^\s*local\s\+mypath=/ s/=.*/=\"${path//\//\\\/}\"/" \
            -e "s/@PREFIX@/${MINGW_PREFIX//\//\\\/}/g" \
            -e "s/@FILENAME@/${profile//\//\\\/}/g" \
            -e "/@REM@/d" \
            "${srcdir}"/perlprofile.in) \
        "${pkgdir}${profile}"

    # Link perl executable to main bin directory
    local perldir="$(dirname "$(find ./bin -name "perl.exe" -print -quit)")"
    if [[ "${perldir}" != ./bin ]]; then
        ln -vt ./bin/ "${perldir}/perl"{.exe,5*.dll}
    fi

    # Add these so we have them on PATH before installing the first package
    sed -nr "s/^install(vendor|site)(bin|script|lib|arch|(man|html)[13]dir)='@PERL_.*?@(.*)'/\\4/p" "${config_heavy}" \
        | sort | uniq | while IFS='' read -r p; do p="${pkgdir}${p//\\/\/}"; [[ -e "${p}" ]] || echo "${p}"; done \
        | xargs -r install -dvm755

    # Licenses
    install -Dvm644 -t "share/licenses/${_realname}" "${srcdir}/${_build}/"{README,Copying,Artistic}

}

# vim: set ts=4 sw=4 et ai:
